﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using DMS.Library.Extensions;

namespace DMS.BO.Web.Mvc
{
    public static class HtmlHelperExtension
    {
        
        public static MvcHtmlString EnumDropDownList(this HtmlHelper htmlHelper, string name, object selectValue, Type enumType, bool createEmptyItem = true, string emptyItemValue = "", object htmlAttributes = null, string emptyItemText = "")
        {

            int outPut;
            var isNotEnum = selectValue == null || int.TryParse(selectValue.ToString(), out outPut);
            // build item list
            IEnumerable<Enum> values = Enum.GetValues(enumType).Cast<Enum>();

            var items = new List<SelectListItem>();
            foreach (var value in values)
            {

                string text = SR.ResourceManager.GetEnumString(value);
                if (string.IsNullOrWhiteSpace(text))
                    text = value.ToString();
                items.Add(new SelectListItem
                {
                    Text = text,
                    Value = isNotEnum ? ((int)Enum.Parse(enumType, value.ToString())).ToString() : Enum.Parse(enumType, value.ToString()).ToString(),
                    Selected = selectValue != null && ((int)Enum.Parse(enumType, value.ToString())) == (int.Parse(selectValue.ToString()))
                });
            }

            if (createEmptyItem)
            {
                items.Insert(0, new SelectListItem { Text = string.IsNullOrWhiteSpace(emptyItemText) ? @"--- Vui lòng chọn ---" : emptyItemText, Value = emptyItemValue });
            }

            return htmlHelper.DropDownList(name, items.AsEnumerable(), htmlAttributes);
        }
    }
}